package com.example.demo.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.common.domain.CommonResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "1 文件上传")
@RestController
public class UploadController {
	@Value("${file.upload.path}")
    private String path;
	
	private String getPath() {
		if(!path.endsWith("/")) {
			path += "/";
        }
		return path;
	}

    @ApiOperation(value = "测试上传单文件")
    @PostMapping("/upload1")
    @ResponseBody
    public CommonResult create1(@RequestPart MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String filePath = getPath() + fileName;

        File dest = new File(filePath);
        Files.copy(file.getInputStream(), dest.toPath());
        return CommonResult.ok("Upload file success", dest.getAbsolutePath());
    }

    @ApiOperation(value = "测试上传多文件")
    @PostMapping("/upload2")
    @ResponseBody
    public CommonResult create2(@RequestPart MultipartFile[] files) throws IOException {
        String[] message = new String[files.length];
        int i = 0;
        
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String filePath = getPath() + fileName;

            File dest = new File(filePath);
            Files.copy(file.getInputStream(), dest.toPath());
            message[i++] = dest.getAbsolutePath();
        }
        return CommonResult.ok("Upload file success", message);
    }
}
